package jlfm.lastfm.apps.recorder;

import java.io.File;

import jlfm.lastfm.client.TrackMetadata;

public class SimplePatternFileNameProvider implements FileNameProvider {

	public final static String ARTIST = "%Artist";

	public final static String ALBUM = "%Album";

	public final static String TRACK = "%Track";

	public final static String STATION = "%Station";

	public final char[] ILLEGAL_FILENAME_CHARS = new char[] { '/', '\\', ':',
			'*', '?', '"', '<', '>', '|' };

	private String fileNamePattern;

	public SimplePatternFileNameProvider(String fileNamePattern) {
		this.fileNamePattern = fileNamePattern;
	}

	public File getOutputFile(TrackMetadata m) {
		return new File(getOutputFileName(m));
	}

	public String getOutputFileName(TrackMetadata m) {
		String fName = fileNamePattern;

		String artist = m.getArtist();
		String album = m.getAlbum();
		String track = m.getTrack();
		String station = m.getStationName();

		fName = getOutputFileName(artist, album, track, station);

		return fName;
	}

	public String getOutputFileName(String artist, String album, String track,
			String station) {
		String fileName = fileNamePattern;
		fileName = replace(fileName, ARTIST, replaceIllegalChars(artist));
		fileName = replace(fileName, ALBUM, replaceIllegalChars(album));
		fileName = replace(fileName, TRACK, replaceIllegalChars(track));
		fileName = replace(fileName, STATION, replaceIllegalChars(station));
		return fileName;
	}

	private String replace(String f, String key, String value) {
		if (f.indexOf(key) > -1) {
			f = f.replaceAll(key, value);
		}
		return f;
	}

	protected String replaceIllegalChars(String s) {
		for (int i = 0; i < ILLEGAL_FILENAME_CHARS.length; i++) {
			s = s != null ? s.replace(ILLEGAL_FILENAME_CHARS[i], ' ') : "";
		}

		return s;
	}

	public String getFileNamePattern() {
		return fileNamePattern;
	}

	public void setFileNamePattern(String fileNamePattern) {
		this.fileNamePattern = fileNamePattern;
	}

}
